package org.zeapp.opencloud.framework.preference;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Implementation of the Preference framework using java Properties files.
 * 
 * @author Amphiprion
 * 
 */
public class PropertiesPreference implements Preference {
	private String filename;
	private Properties properties;

	/**
	 * Build a new Preference object.
	 * 
	 * @param filename
	 *            the filename of the properties.
	 */
	public PropertiesPreference(String filename) {
		this.filename = filename;
		properties = new Properties();
		try {
			properties.load(new FileInputStream(filename));
		} catch (FileNotFoundException e) {
			// can be normal (first time)
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void set(String key, String value) {
		properties.setProperty(key, value);
	}

	@Override
	public void set(String key, int value) {
		properties.setProperty(key, "" + value);
	}

	@Override
	public String get(String key) {
		return properties.getProperty(key);
	}

	@Override
	public String get(String key, String defaultValue) {
		if (properties.containsKey(key)) {
			return properties.getProperty(key);
		}
		return defaultValue;
	}

	@Override
	public int getInt(String key, int defaultValue) {
		String value = get(key);
		if (value == null) {
			return defaultValue;
		} else {
			try {
				return Integer.parseInt(value);
			} catch (Throwable e) {
				return defaultValue;
			}
		}
	}

	@Override
	public boolean commit() {
		try {
			properties
					.store(new FileOutputStream(filename),
							"Generated by org.zeapp.opencloud.framework.preference.PropertiesPreference");
			return true;
		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		}
	}
}
